/*
 * =====================================================================================
 *
 *       Filename:  cl_channel.cxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  03/30/2011 08:00:23 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Chen Ken (Ken), zlchen.ken@gmail.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include "cl_channel.hxx"

namespace neo
{
CLChannel::CLChannel(int fd, unsigned int events) 
  : m_fd(fd),
  m_events(events),
  m_readyEvents(CL_NONE_EVENT) 
{
}

void CLChannel::handleEvent(void)
{
  if((m_readyEvents & POLLHUP) && !(m_readyEvents & POLLIN))
  {
		if(m_closeCallback)
		{
  	  m_closeCallback();
		}
  }

  if(m_readyEvents & (POLLERR | POLLNVAL))
  {
	  if(m_errorCallback)
		{
  	  m_errorCallback();
		}
  }

  if(m_readyEvents & (POLLIN | POLLPRI | POLLRDHUP))
  {
    if(m_readCallback)
		{
      m_readCallback();
		}
  }

  if(m_readyEvents & POLLOUT)
  {
    if(m_writeCallback)
		{
  	  m_writeCallback();
		}
  }
}

void CLChannel::setReadCallback(const CLCallbackFunctor& cb) 
{
  m_readCallback = cb;
}

void CLChannel::setWriteCallback(const CLCallbackFunctor& cb) 
{
  m_writeCallback = cb;
}

void CLChannel::setCloseCallback(const CLCallbackFunctor& cb) 
{
  m_closeCallback = cb;
}

void CLChannel::setErrorCallback(const CLCallbackFunctor& cb) 
{
  m_errorCallback = cb;
}

void CLChannel::setReadyEvents(unsigned int readyEvents) 
{
  m_readyEvents = readyEvents;
}

void CLChannel::enableReading(void) 
{
  m_events |= CL_READ_EVENT; 
}

void CLChannel::enableWriting(void) 
{
  m_events |= CL_WRITE_EVENT;
}

void CLChannel::disableReading(void) 
{
  m_events &= (~CL_READ_EVENT);
}

void CLChannel::disableWriting(void) 
{
  m_events &= (~CL_WRITE_EVENT);
}

void CLChannel::disableAll(void) 
{
  m_events = CL_NONE_EVENT;
}

bool CLChannel::isWriteEnabled(void) const
{
  return ((m_events & CL_WRITE_EVENT) == CL_NONE_EVENT);
}

bool CLChannel::isReadEnabled(void) const
{
  return ((m_events & CL_READ_EVENT) == CL_NONE_EVENT);
}

unsigned int CLChannel::events(void) const 
{
  return m_events;
}

int CLChannel::fd(void) const 
{
  return m_fd;
}

} // neo

